package com.zhuchaooasystem.ui.home.service;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.adapter.holder.ServiceImageHolder;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.ServiceImageDeleteEntity;
import com.zhuchaooasystem.entity.ServiceImageEntity;
import com.zhuchaooasystem.event.ServiceDetailEvent;
import com.zhuchaooasystem.presenter.home.serviceimage.ServiceImageContract;
import com.zhuchaooasystem.presenter.home.serviceimage.ServiceImagePresenter;
import com.zhuchaooasystem.ui.common.LocalAlbumActivity;
import com.zhuchaooasystem.utils.AppUtils;
import com.zhuchaooasystem.utils.CameraUtils;
import com.zhuchaooasystem.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class ServiceImageActivity extends BaseActivity<ServiceImagePresenter> implements ServiceImageContract.View {
    private final int UPLOAD_IMAGE_MAX = 9;

    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    @BindView(R.id.actionbar_iv_right)
    ImageView iv_edit;
    @BindView(R.id.actionbar_iv_right_finish)
    ImageView iv_finish;
    @BindView(R.id.actionbar_iv_right1)
    ImageView iv_add;
    //----
    @BindView(R.id.act_service_image_recycle)
    EasyRecyclerView recycle;
    @BindView(R.id.act_service_image_linear_menu)
    LinearLayout linear_menu;
    @BindView(R.id.act_service_image_txt_all)
    TextView txt_all;
    @BindView(R.id.act_service_image_txt_desc)
    TextView txt_desc;
    @BindView(R.id.act_service_image_txt_delete)
    TextView txt_delete;

    //----每行放置的图片个数
    private int numColomn = 2;
    private CameraUtils util_camera;
    //----选中的图片路径列表
    private List<Integer> checkPositionlist; //选中图片位置的列表
    private ArrayList<String> imageChoosedList; //选中的图片列表
    //----
    private boolean showCheck;
    private boolean selectAll;
    private List<ServiceImageEntity.ResultBean.SuccessfulBean.PathContentBean> pathList;
    private ArrayList<String> imageList;
    private RecyclerArrayAdapter adapter;
    //---
    private boolean canEdit;
    private int projectId;
    private String orderCode;

    @Override
    protected int getLayout() {
        return R.layout.activity_service_image;
    }

    @Override
    protected ServiceImagePresenter getPresenter() {
        return new ServiceImagePresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        if (null != getIntent() && null != getIntent().getExtras()) {
            canEdit = getIntent().getExtras().getBoolean("canEdit");
            projectId = getIntent().getExtras().getInt("projectId", 0);
            orderCode = getIntent().getExtras().getString("orderCode");
        }
        util_camera = new CameraUtils();
        RxBus.get().register(this);
        imageChoosedList = new ArrayList<>();
        checkPositionlist = new ArrayList<>();
        showCheck = false;
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("localAlbum")})
    public void localAlbum(BaseEvent baseEvent) {
        if (null != baseEvent && null != baseEvent.event) {
            List<String> imageList = (List<String>) baseEvent.event;
            mPresenter.uploadImage(imageList);
        }
    }

    @Override
    protected void initView() {
        setActionBar();
        //----
        initRecycle();
    }

    private void initRecycle() {
        //----
        recycle.setLayoutManager(new GridLayoutManager(mContext, numColomn));
        recycle.setAdapterWithProgress(adapter = new RecyclerArrayAdapter<String>(mContext) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ServiceImageHolder(parent, ServiceImageActivity.this);
            }
        });
    }

    private void setActionBar() {
        txt_title.setText(getString(R.string.actionbar_title_service_image_manage));
        iv_back.setVisibility(View.VISIBLE);
        if (canEdit) {
            iv_add.setImageResource(R.drawable.ic_add);
            iv_edit.setImageResource(R.drawable.ic_edit);
            iv_add.setVisibility(View.VISIBLE);
            iv_edit.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void initDataAndLoadData() {
        mPresenter.getImage();
    }

    @OnClick({R.id.actionbar_iv_back, R.id.actionbar_iv_right, R.id.actionbar_iv_right1, R.id.actionbar_iv_right_finish, R.id.act_service_image_txt_all, R.id.act_service_image_txt_delete})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                finish();
                break;
            //添加按钮
            case R.id.actionbar_iv_right1:
                mPresenter.showPickDialog();
                break;
            //完成按钮
            case R.id.actionbar_iv_right_finish:
                iv_add.setVisibility(View.VISIBLE);
                iv_edit.setVisibility(View.VISIBLE);
                iv_finish.setVisibility(View.GONE);
                linear_menu.setVisibility(View.GONE);
                showCheck = false;
                adapter.notifyDataSetChanged();
                break;
            //编辑按钮
            case R.id.actionbar_iv_right:
                iv_add.setVisibility(View.GONE);
                iv_edit.setVisibility(View.GONE);
                iv_finish.setVisibility(View.VISIBLE);
                linear_menu.setVisibility(View.VISIBLE);
                showCheck = true;
                adapter.notifyDataSetChanged();
                break;
            //全选按钮
            case R.id.act_service_image_txt_all:
                if (txt_all.getText().toString().equals("全选")) {
                    txt_all.setText("全不选");
                    txt_desc.setText("已选" + imageList.size() + "/" + imageList.size());
                    if (null != imageChoosedList && imageChoosedList.size() > 0) {
                        imageChoosedList.clear();
                    }
                    if (null != checkPositionlist && checkPositionlist.size() > 0) {
                        checkPositionlist.clear();
                    }
                    for (int i = 0; i < imageList.size(); i++) {
                        imageChoosedList.add(imageList.get(i));
                        checkPositionlist.add(i);
                    }
                    //----
                    selectAll = true;
                } else {
                    txt_all.setText("全选");
                    txt_desc.setText("已选" + "0/" + imageList.size());
                    if (null != imageChoosedList && imageChoosedList.size() > 0) {
                        imageChoosedList.clear();
                    }
                    if (null != checkPositionlist && checkPositionlist.size() > 0) {
                        checkPositionlist.clear();
                    }
                    //----
                    selectAll = false;
                }
                adapter.notifyDataSetChanged();
                break;
            //删除按钮
            case R.id.act_service_image_txt_delete:
                if (null != checkPositionlist && checkPositionlist.size() > 0) {
                    mPresenter.deleteImage();
                } else {
                    ToastUtil.showShort(mContext, "请选择至少一张图片进行删除");
                }
                break;
        }
    }


    @Override
    public int getProjectId() {
        return projectId;
    }

    @Override
    public String getOrderCode() {
        return orderCode;
    }

    @Override
    public void refreshData(List<ServiceImageEntity.ResultBean.SuccessfulBean> serviceImageList) {
        this.pathList = mPresenter.getServiceImageList(serviceImageList);
        this.imageList = mPresenter.getArrayImageList(serviceImageList);
        txt_desc.setText("已选" + "0/" + imageList.size());
        adapter.clear();
        adapter.addAll(pathList);
    }

    @Override
    public void onCameraClick() {
        //拍照权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            requestPermission(new String[]{Manifest.permission.CAMERA}, Key.CAMERA);
        } else {
            //----拍照
            util_camera.takePhoto(mContext);
        }
    }

    @Override
    public void onAlbumClick() {
        //----本地上传
        Bundle bundle = new Bundle();
        bundle.putInt("image_max", UPLOAD_IMAGE_MAX);
        bundle.putInt("image_cur", 0);
        AppUtils.jump(mContext, LocalAlbumActivity.class, bundle);
    }

    @Override
    public void submitSuccuss() {
        ToastUtil.showShort(mContext, "上传成功");
        mPresenter.getImage();
        RxBus.get().post("RedactToDetail", new ServiceDetailEvent());
    }

    @Override
    public String getServiceId() {
        String ids = "";
        for (int i = 0; i < pathList.size(); i++) {
            if (checkPositionlist.contains(i)) {
                ids += pathList.get(i).getUid() + ",";
            }
        }
        return ids.substring(0, ids.length() - 1);
    }

    @Override
    public void deleteSuccuss(ServiceImageDeleteEntity.ResultBean entity) {
        ToastUtil.showShort(mContext, "删除成功");
        if (null != imageChoosedList && imageChoosedList.size() > 0) {
            imageChoosedList.clear();
        }
        if (null != checkPositionlist && checkPositionlist.size() > 0) {
            checkPositionlist.clear();
        }
        selectAll = false;
        txt_all.setText("全选");
        mPresenter.getImage();
        RxBus.get().post("RedactToDetail", new ServiceDetailEvent());
    }

    public void setTxtDesc(int size) {
        txt_desc.setText("已选" + size + "/" + imageList.size());
    }

    public ArrayList<String> getImageList() {
        return imageList;
    }

    public void setImageList(ArrayList<String> imageList) {
        this.imageList = imageList;
    }

    public int getNumColomn() {
        return numColomn;
    }

    public void setNumColomn(int numColomn) {
        this.numColomn = numColomn;
    }

    public List<Integer> getCheckPositionlist() {
        return checkPositionlist;
    }

    public void setCheckPositionlist(List<Integer> checkPositionlist) {
        this.checkPositionlist = checkPositionlist;
    }

    public ArrayList<String> getImageChoosedList() {
        return imageChoosedList;
    }

    public void setImageChoosedList(ArrayList<String> imageChoosedList) {
        this.imageChoosedList = imageChoosedList;
    }

    public boolean isShowCheck() {
        return showCheck;
    }

    public void setShowCheck(boolean showCheck) {
        this.showCheck = showCheck;
    }

    public boolean isSelectAll() {
        return selectAll;
    }

    public void setSelectAll(boolean selectAll) {
        this.selectAll = selectAll;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }

    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case Key.CAMERA:
                //----拍照
                util_camera.takePhoto(mContext);
                break;
        }
    }

    /**
     * 权限失败回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            String path = CameraUtils.imagePath;
            List<String> imageList = new ArrayList<>();
            imageList.add(path);
            mPresenter.uploadImage(imageList);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode()== KeyEvent.KEYCODE_BACK && event.getAction()== MotionEvent.ACTION_UP){
            if(canEdit && iv_finish.getVisibility()==View.VISIBLE){
                iv_add.setVisibility(View.VISIBLE);
                iv_edit.setVisibility(View.VISIBLE);
                iv_finish.setVisibility(View.GONE);
                linear_menu.setVisibility(View.GONE);
                showCheck = false;
                adapter.notifyDataSetChanged();
                if (null != imageChoosedList && imageChoosedList.size() > 0) {
                    imageChoosedList.clear();
                }
                if (null != checkPositionlist && checkPositionlist.size() > 0) {
                    checkPositionlist.clear();
                }
                return false;
            }
        }
        return super.dispatchKeyEvent(event);
    }
}
